<template>
  <div class="online-batch">
    <!-- 批量操作 -->
    <div class="operation-select">
      <!-- 播放按钮 -->
      <CommonButton
        icon="&#xea6e;"
        name="播放"
        class="play"
        @click="playSelect"
      ></CommonButton>
      <!-- 取消操作按钮 -->
      <CommonButton
        icon="&#xe617;"
        name="取消操作"
        @click="emits('closeSelect', false)"
        class="cancel"
      ></CommonButton>
    </div>
    <SongTable
      :songs="songs"
      :song-id-mapper="songIdMapper"
      :show-select="true"
      :show-header="false"
      @get-select-items="getSelectItems"
    ></SongTable>
  </div>
</template>

<script setup lang="ts">
import CommonButton from '@/components/button/common-button/index.vue'
import SongTable from '@/components/table/song-table/index.vue'
import useFooterStore from '@/store/footer'
import useUserStore from '@/store/user'
import { elMessage, getTheme } from '@/utils'
import { storeToRefs } from 'pinia'
import { Song } from '@/model'
import { nextTick, reactive } from 'vue'
import { elMessageType } from '@/model/enum'

// 配置主题
const themeColor = getTheme().get('themeColor')

const footer = useFooterStore()
const { isPlay, songList, songListId, playProcess, playTime, current } =
  storeToRefs(footer)
const user = useUserStore()

defineProps<{
  // 歌曲
  songs: Song[]
  // 歌曲id与index对应的Map
  songIdMapper: Map<string, number>
}>()

const emits = defineEmits<{
  (e: 'closeSelect', showSelect: boolean): void
}>()

// 选择的歌曲
const selectSongs = reactive<Song[]>([])
// 获取选择的歌曲
const getSelectItems = (songs: Song[]) => {
  if (selectSongs.length != 0) {
    // 清空已选择的
    selectSongs.splice(0)
  }
  selectSongs.push(...songs)
}

// 播放选择的
const playSelect = async () => {
  if (selectSongs.length > 0) {
    // 当前的音乐暂停
    isPlay.value = false
    playProcess.value = 0
    playTime.value = 0
    await nextTick()
    selectSongs.forEach((item) => {
      const index = songListId.value.get(item.id)
      // 如果歌曲列表里面，没有这个歌，就把这个歌添加到歌曲列表中
      if (index == undefined) {
        songList.value.unshift(item)
      }
    })
    current.value = songListId.value.get(selectSongs[0].id) as number
    isPlay.value = true
    elMessage(elMessageType.SUCCESS, '已经添加到播放列表!')
  } else {
    elMessage(elMessageType.INFO, '请添加歌曲!')
  }
}
</script>

<style lang="less" scoped>
@theme-color: v-bind(themeColor);
@color-white: #ffffff;
.operation-select {
  margin: 15px 10px;
  width: 80vw;

  .el-button {
    font-size: 13px;
    width: 100px !important;
  }
  .play {
    background-color: @theme-color;
    color: @color-white;
  }
}
</style>
